﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Xml;
using System.Runtime.Serialization;
using System.Drawing;
using System.Drawing.Imaging;
//using NPinyin;
using Pinyin4net;
using Pinyin4net.Format;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Dynamic;
using System.Text.RegularExpressions;
using System.Linq.Expressions;

namespace _180FrameWork.Common
{
    public static class MyConvertExtensions
    {
        #region 基础数据类型转换
        /// <summary>
        /// 转换成bool
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool ToBool(this object obj)
        {
            return obj.ToBool(false);
        }
        /// <summary>
        /// 转换成bool
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public static bool ToBool(this object obj, bool DefaultValue)
        {
            bool value = false;
            try
            {
                value = Convert.ToBoolean(obj);
            }
            catch
            {
                value = DefaultValue;
            }
            return value;
        }

        /// <summary>
        /// 转化成int
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ToInt(this object obj)
        {
            return obj.ToInt(0);
        }
        /// <summary>
        /// 转化成int
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DefaultValue">默认值</param>
        /// <returns></returns>
        public static int ToInt(this object obj, int DefaultValue)
        {
            int value = 0;
            try
            {
                value = Convert.ToInt32(obj);
            }
            catch
            {
                value = DefaultValue;
            }
            return value;
        }
        /// <summary>
        /// 转化为int
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DefaultValue"></param>
        /// <param name="MinValue"></param>
        /// <returns></returns>
        public static int ToInt(this object obj, int DefaultValue, int MinValue)
        {
            int value = 0;
            try
            {
                value = Convert.ToInt32(obj);
                if (value < MinValue)
                    value = MinValue;
            }
            catch
            {
                value = DefaultValue;
            }
            return value;
        }
        /// <summary>
        /// 转化为int
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DefaultValue"></param>
        /// <param name="MaxValue"></param>
        /// <param name="MinValue"></param>
        /// <returns></returns>
        public static int ToInt(this object obj, int DefaultValue, int MinValue, int MaxValue)
        {
            int value = 0;
            try
            {
                value = Convert.ToInt32(obj);
                if (value < MinValue)
                    value = MinValue;
                else if (value > MaxValue)
                    value = MaxValue;
            }
            catch
            {
                value = DefaultValue;
            }
            return value;
        }

        /// <summary>
        /// 转化成double
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double ToDb(this object obj)
        {
            return obj.ToDb(0);
        }
        /// <summary>
        /// 转化成double
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DefaultValue">默认值</param>
        /// <returns></returns>
        public static double ToDb(this object obj, double DefaultValue)
        {
            double value = 0;
            try
            {
                value = Convert.ToDouble(obj);
            }
            catch
            {
                value = DefaultValue;
            }
            return value;
        }
        /// <summary>
        /// 转化成decimal
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal ToDec(this object obj)
        {
            return obj.ToDec(0);
        }
        /// <summary>
        /// 转化成decimal
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DefaultValue">默认值</param>
        /// <returns></returns>
        public static decimal ToDec(this object obj, decimal DefaultValue)
        {
            decimal value = 0;
            try
            {
                value = Convert.ToDecimal(obj);
            }
            catch
            {
                value = DefaultValue;
            }
            return value;
        }
        /// <summary>
        /// 转化为date
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DateTime ToDate(this object obj)
        {
            return obj.ToDate(DateTime.Now);
        }
        /// <summary>
        /// 转化为date
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public static DateTime ToDate(this object obj, DateTime DefaultValue)
        {
            DateTime value = DateTime.MinValue;
            try
            {
                value = Convert.ToDateTime(obj);
            }
            catch
            {
                value = DefaultValue;
            }
            return value;
        }
        /// <summary>
        /// 转化为字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToStr(this object obj)
        {
            try
            {
                return obj.ToString().Trim();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 转化为字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string ToStr(this object obj, int length)
        {
            try
            {
                string strValue = obj.ToString().Trim();
                if (strValue.Length > length)
                    return strValue.Substring(0, length);
                return strValue;
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 按字节数截取
        /// </summary>
        /// <param name="originalText"></param>
        /// <param name="bytesAfterCut"></param>
        /// <returns></returns>
        public static string ToStrB(this string originalText, int bytesAfterCut)
        {
            if (originalText != null)
            {
                string optimizedText = originalText;
                byte[] val = Encoding.Default.GetBytes(originalText);
                if (val.Length > bytesAfterCut)
                {
                    int left = bytesAfterCut / 2;
                    int right = bytesAfterCut;
                    left = left > originalText.Length ? originalText.Length : left;
                    right = right > originalText.Length ? originalText.Length : right;
                    while (left < right - 1)
                    {
                        int mid = (left + right) / 2;
                        if (Encoding.Default.GetBytes(originalText.Substring(0, mid)).Length > bytesAfterCut)
                        {
                            right = mid;
                        }
                        else
                        {
                            left = mid;
                        }
                    }
                    byte[] rightVal = Encoding.Default.GetBytes(originalText.Substring(0, right));
                    if (rightVal.Length == bytesAfterCut)
                    {
                        optimizedText = originalText.Substring(0, right);
                    }
                    else
                    {
                        optimizedText = originalText.Substring(0, left);
                    }
                }
                return optimizedText;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 覆盖指定位置字符串
        /// </summary>
        /// <param name="oldStr"></param>
        /// <param name="BeginIndex"></param>
        /// <param name="Length"></param>
        /// <returns></returns>
        public static string CoverString(string oldStr, int BeginIndex, int Length)
        {
            if (oldStr.Length < BeginIndex || oldStr.Length < (BeginIndex + Length))
                return oldStr;
            else
            {
                string CoverStr = oldStr.Substring(BeginIndex, Length);
                string MarkStr = new string('*', Length);
                return oldStr.Replace(CoverStr, MarkStr);
            }
        }
        /// <summary>
        /// 覆盖指定位置字符串
        /// </summary>
        /// <param name="oldStr"></param>
        /// <param name="BeginIndex"></param>
        /// <returns></returns>
        public static string CoverString(string oldStr, int BeginIndex)
        {
            if (oldStr.Length < BeginIndex)
                return oldStr;
            else
            {
                string CoverStr = oldStr.Substring(BeginIndex);
                return oldStr.Replace(CoverStr, "*");
            }
        }
        #endregion

        #region List转换
        /// <summary>
        /// 数组转化为datatable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ResList"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(this IList<T> ResList)
        {
            //取得 UsersAttribute類別中的成員名稱和屬性型別
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));

            //新增DataTable欄位名稱和型別
            DataTable dt = new DataTable();

            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                switch (prop.PropertyType.Name.ToLower())
                {
                    case "bool":
                    case "boolean":
                        dt.Columns.Add(prop.Name, typeof(bool));
                        break;
                    case "int32":
                        dt.Columns.Add(prop.Name, typeof(Int32));
                        break;
                    case "string":
                        dt.Columns.Add(prop.Name, typeof(string));
                        break;
                    case "decimal":
                        dt.Columns.Add(prop.Name, typeof(decimal));
                        break;
                    case "datetime":
                        dt.Columns.Add(prop.Name, typeof(DateTime));
                        break;
                    case "nullable`1":
                        //判断fullname
                        if (prop.PropertyType.FullName.ToLower().Contains("datetime"))
                            dt.Columns.Add(prop.Name, typeof(DateTime));
                        else if (prop.PropertyType.FullName.ToLower().Contains("bool"))
                            dt.Columns.Add(prop.Name, typeof(bool));
                        else if (prop.PropertyType.FullName.ToLower().Contains("boolean"))
                            dt.Columns.Add(prop.Name, typeof(bool));
                        else if (prop.PropertyType.FullName.ToLower().Contains("int32"))
                            dt.Columns.Add(prop.Name, typeof(Int32));
                        else if (prop.PropertyType.FullName.ToLower().Contains("string"))
                            dt.Columns.Add(prop.Name, typeof(string));
                        else if (prop.PropertyType.FullName.ToLower().Contains("decimal"))
                            dt.Columns.Add(prop.Name, typeof(decimal));
                        break;
                }
            }
            //新增資料
            object[] values = new object[props.Count];
            foreach (var item in ResList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }
        /// <summary>
        /// datatable转化为数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(this DataTable dt) where T : new()
        {
            //取得 UsersAttribute類別中的成員名稱和屬性型別
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            List<T> list = new List<T>();
            foreach (DataRow DR in dt.Rows)
            {
                T item = new T();
                for (int i = 0; i < props.Count; i++)
                {
                    PropertyDescriptor prop = props[i];
                    if (dt.Columns.Contains(prop.Name.ToLower()))
                    {
                        switch (prop.PropertyType.Name.ToLower())
                        {
                            case "bool":
                            case "boolean":
                                prop.SetValue(item, DR[prop.Name].ToBool());
                                break;
                            case "int32":
                                prop.SetValue(item, DR[prop.Name].ToInt());
                                break;
                            case "string":
                                prop.SetValue(item, DR[prop.Name].ToStr());
                                break;
                            case "decimal":
                                prop.SetValue(item, DR[prop.Name].ToDec());
                                break;
                            case "datetime":
                                prop.SetValue(item, DR[prop.Name].ToDate());
                                break;
                            case "nullable`1":
                                if (DR[prop.Name] != DBNull.Value)
                                {
                                    //判断fullname
                                    if (prop.PropertyType.FullName.ToLower().Contains("datetime"))
                                        prop.SetValue(item, DR[prop.Name].ToDate());
                                    else if (prop.PropertyType.FullName.ToLower().Contains("bool"))
                                        prop.SetValue(item, DR[prop.Name].ToBool());
                                    else if (prop.PropertyType.FullName.ToLower().Contains("boolean"))
                                        prop.SetValue(item, DR[prop.Name].ToBool());
                                    else if (prop.PropertyType.FullName.ToLower().Contains("int32"))
                                        prop.SetValue(item, DR[prop.Name].ToInt());
                                    else if (prop.PropertyType.FullName.ToLower().Contains("string"))
                                        prop.SetValue(item, DR[prop.Name].ToStr());
                                    else if (prop.PropertyType.FullName.ToLower().Contains("decimal"))
                                        prop.SetValue(item, DR[prop.Name].ToDec());
                                }
                                break;
                        }
                    }
                }
                list.Add(item);
            }
            return list;
        }
        /// <summary>
        /// datatable第一行转化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static T FirstRowToObject<T>(this DataTable dt) where T : new()
        {
            List<T> list = dt.DataTableToList<T>();
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return default(T);
            }
        }
        /// <summary>
        /// 行转换成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T RowToObject<T>(this DataRow dr) where T : new()
        {
            //取得 UsersAttribute類別中的成員名稱和屬性型別
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            T item = new T();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                if (dr.Table.Columns.Contains(prop.Name.ToLower()))
                {
                    switch (prop.PropertyType.Name.ToLower())
                    {
                        case "bool":
                        case "boolean":
                            prop.SetValue(item, dr[prop.Name].ToBool());
                            break;
                        case "int32":
                            prop.SetValue(item, dr[prop.Name].ToInt());
                            break;
                        case "string":
                            prop.SetValue(item, dr[prop.Name].ToStr());
                            break;
                        case "decimal":
                            prop.SetValue(item, dr[prop.Name].ToDec());
                            break;
                        case "datetime":
                            prop.SetValue(item, dr[prop.Name].ToDate());
                            break;
                        case "nullable`1":
                            if (dr[prop.Name] != DBNull.Value)
                            {
                                //判断fullname
                                if (prop.PropertyType.FullName.ToLower().Contains("datetime"))
                                    prop.SetValue(item, dr[prop.Name].ToDate());
                                else if (prop.PropertyType.FullName.ToLower().Contains("bool"))
                                    prop.SetValue(item, dr[prop.Name].ToBool());
                                else if (prop.PropertyType.FullName.ToLower().Contains("boolean"))
                                    prop.SetValue(item, dr[prop.Name].ToBool());
                                else if (prop.PropertyType.FullName.ToLower().Contains("int32"))
                                    prop.SetValue(item, dr[prop.Name].ToInt());
                                else if (prop.PropertyType.FullName.ToLower().Contains("string"))
                                    prop.SetValue(item, dr[prop.Name].ToStr());
                                else if (prop.PropertyType.FullName.ToLower().Contains("decimal"))
                                    prop.SetValue(item, dr[prop.Name].ToDec());
                            }
                            break;
                    }
                }
            }
            return item;
        }
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="DTOld"></param>
        ///// <param name="cols"></param>
        ///// <returns></returns>
        //public static DataTable DataTableToNewDataTable(this DataTable DTOld, IDictionary<string, string> cols)
        //{
        //    DataTable DTNew = DTOld.Copy();
        //    foreach (DataColumn DCOld in DTOld.Columns)
        //    {
        //        DataColumn DCNew = DTNew.Columns[DCOld.ColumnName];
        //        if (cols.ContainsKey(DCNew.ColumnName))
        //        {
        //            DCNew.ColumnName = cols[DCNew.ColumnName];
        //        }
        //        else
        //        {
        //            DTNew.Columns.Remove(DCNew);
        //        }
        //    }
        //    //DataTable DT
        //    return DTNew;
        //}
        /// <summary>
        /// datatable重命名列
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="cols"></param>
        public static void DataTableReName(this DataTable dt, string[] cols)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                DataColumn dc = dt.Columns[i];
                if (cols.Length > i)
                {
                    dc.ColumnName = cols[i];
                }
            }
        }

        #endregion

        #region json转换
        /// <summary>
        /// 对象转化为json格式
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjToJson(this Object obj)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            //timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss";
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        /// <summary>
        /// json格式转化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T JsonToObj<T>(this string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
        /// <summary>
        /// 将数据集中第一个表的数据导出成为json格式
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string DataSetToJson(this DataSet ds)
        {
            if (ds.Tables.Count > 0)
            {
                DataTable DT = ds.Tables[0];
                return JsonConvert.SerializeObject(DT, new DataTableConverter());
            }
            else
                return "";
        }

        //public static dynamic JsonToDynamic(this string json)
        //{
        //    return JsonConvert.DeserializeObject<ExpandoObject>(json);
        //}
        #endregion

        #region 二进制转换

        public static bool ObjToBinary(Object obj, string strFilePath)
        {
            using (FileStream fs = new FileStream(strFilePath, FileMode.Create))
            {
                BinaryFormatter f = new BinaryFormatter();
                f.Serialize(fs, obj);
                return true;
            }
        }

        public static T BinaryToObj<T>(string strFilePath)
        {
            T t;
            using (FileStream fs = new FileStream(strFilePath, FileMode.Open))
            {
                BinaryFormatter f = new BinaryFormatter();
                t = (T)f.Deserialize(fs);
            }
            return t;
        }

        #endregion

        #region xml转换
        /// <summary>
        /// 对象转化为xml格式
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjToXML(this Object obj)
        {
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
            //    {
            //        DataContractSerializer ser = new DataContractSerializer(obj.GetType());
            //        ser.WriteObject(xw, obj);
            //        byte[] buffer = ms.ToArray();
            //        // 获取XML文档的内容
            //        string xml = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            //        //ms.Close();
            //        return xml;
            //    }
            //}
            using (MemoryStream ms = new MemoryStream())
            {
                XmlSerializer ser = new XmlSerializer(obj.GetType());
                ser.Serialize(ms, obj);
                byte[] buffer = ms.ToArray();
                // 获取XML文档的内容
                string xml = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                ms.Close();
                return xml;
            }
        }
        /// <summary>
        /// xml格式转化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strxml"></param>
        /// <returns></returns>
        public static T XMLToObj<T>(this string strxml)
        {
            //using (StringReader ms = new StringReader(strxml))
            //{
            //    using (XmlReader xr = XmlTextReader.Create(ms))
            //    {
            //        DataContractSerializer ser = new DataContractSerializer(typeof(T));
            //        T t = (T)ser.ReadObject(xr);
            //        //ms.Close();
            //        return t;
            //    }
            //}
            using (StringReader ms = new StringReader(strxml))
            {
                XmlSerializer ser = new XmlSerializer(typeof(T));
                T t = (T)ser.Deserialize(ms);
                ms.Close();
                return t;
            }
        }
        #endregion

        #region 十六进制转换
        /// <summary>
        /// 十六进制字符串转二进制数组
        /// </summary>
        /// <param name="hex"></param>
        /// <returns></returns>
        public static byte[] hexStringToByte(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }
        /// <summary>
        /// 二进制数组转十六进制字符串
        /// </summary>
        /// <param name="ba"></param>
        /// <returns></returns>
        public static string byteToHexString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

        #endregion

        #region 特殊转换

        /// <summary>
        /// 字符串转换成字典
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static IDictionary<string, string> StringToDict(string str)
        {
            IDictionary<string, string> Dict = new Dictionary<string, string>();
            //1次拆分
            string[] strList = str.Split(new string[] { ",", "|", ";" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string strItem in strList)
            {
                //2次拆分
                string[] strKeyValue = strItem.Split(new string[] { ":", "/" }, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    string strKey = strKeyValue[0];
                    string strValue = strKeyValue[1];
                    if (Dict.ContainsKey(strKey))
                    {
                        Dict[strKey] = strValue;
                    }
                    else
                    {
                        Dict.Add(strKey, strValue);
                    }
                }
                catch
                {
                }
            }
            return Dict;
        }
        /// <summary>
        /// 字典转换成字符串
        /// </summary>
        /// <param name="Dict"></param>
        /// <param name="KeyValueSplitString">连接字符</param>
        /// <param name="ItemSplitString">分割字符</param>
        /// <returns></returns>
        public static string DictToString(IDictionary<string, string> Dict, string KeyValueSplitString, string ItemSplitString)
        {
            StringBuilder str = new StringBuilder();
            foreach (string strKey in Dict.Keys)
            {
                if (str.Length == 0)
                    str.Append(string.Format("{0}{1}{2}", new object[] { strKey, KeyValueSplitString, Dict[strKey], ItemSplitString }));
                else
                    str.Append(string.Format("{3}{0}{1}{2}", new object[] { strKey, KeyValueSplitString, Dict[strKey], ItemSplitString }));
            }
            return str.ToString();
        }
        #endregion

        #region 拼音转换

        /// <summary>
        /// 是否中文字符
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsChanese(char c)
        {
            if (c >= 0x4e00 && c <= 0x9fbb)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 是否英文字符
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsEnglish(char c)
        {
            if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 是否数字
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsNumber(char c)
        {
            if (c >= '0' && c <= '9')
                return true;
            else
                return false;
        }

        /// <summary>
        /// 中文字符转拼音
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static string ChineseToPinyin(string strChinese, bool withNumber = false, bool withEnglish = true)
        {
            try
            {
                #region pinyin4net

                HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
                format.ToneType = HanyuPinyinToneType.WITHOUT_TONE;
                StringBuilder strReturn = new StringBuilder();
                foreach (var c in strChinese)
                {
                    if (IsChanese(c))
                    {
                        var pyList = PinyinHelper.ToHanyuPinyinStringArray(c, format);
                        string firstPy = "";
                        foreach (var py in pyList)
                        {
                            if (py != null)
                            {
                                firstPy = py.ToUpper();
                                break;
                            }
                        }
                        strReturn.Append(firstPy);
                    }
                    else if (IsEnglish(c) && withEnglish)
                    {
                        strReturn.Append(Char.ToUpper(c));
                    }
                    else if (IsNumber(c) && withNumber)
                    {
                        strReturn.Append(c);
                    }
                }
                return strReturn.ToString();

                #endregion
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 中文字符转拼音(多音字处理)
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static IList<string> ChineseToPinyinList(string strChinese)
        {
            try
            {
                HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
                format.ToneType = HanyuPinyinToneType.WITHOUT_TONE;
                string root = "";
                IList<string> PinyinList = new List<string>();
                CreatePinyinList(root, strChinese, format, PinyinList);
                return PinyinList;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 中文字符转拼音首字母
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static string ChineseToInitials(string strChinese, bool withNumber = false, bool withEnglish = true)
        {
            try
            {
                HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
                format.ToneType = HanyuPinyinToneType.WITHOUT_TONE;
                StringBuilder strReturn = new StringBuilder();
                foreach (var c in strChinese)
                {
                    if (IsChanese(c))
                    {
                        var pyList = PinyinHelper.ToHanyuPinyinStringArray(c, format);
                        string firstPy = "";
                        foreach (var py in pyList)
                        {
                            if (py != null)
                            {
                                firstPy = py.Substring(0, 1).ToUpper();
                                break;
                            }
                        }
                        strReturn.Append(firstPy);
                    }
                    else if (IsEnglish(c) && withEnglish)
                    {
                        strReturn.Append(Char.ToUpper(c));
                    }
                    else if (IsNumber(c) && withNumber)
                    {
                        strReturn.Append(c);
                    }
                }
                return strReturn.ToString();
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 中文字符转拼音首字母(多音字处理)
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static IList<string> ChineseToInitialsList(string strChinese)
        {
            try
            {
                HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
                format.ToneType = HanyuPinyinToneType.WITHOUT_TONE;
                string root = "";
                IList<string> InitialsList = new List<string>();
                CreateInitialsList(root, strChinese, format, InitialsList);
                return InitialsList;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 递归生成拼音列表
        /// </summary>
        /// <param name="root"></param>
        /// <param name="strChinese"></param>
        /// <param name="format"></param>
        /// <param name="PinyinList"></param>
        private static void CreatePinyinList(string root, string strChinese, HanyuPinyinOutputFormat format, IList<string> PinyinList)
        {
            //取第一个字符
            char c = strChinese[0];
            //取剩余字符
            string nextStrChinese = strChinese.Substring(1, strChinese.Length - 1);

            var pyArray = PinyinHelper.ToHanyuPinyinStringArray(c, format);
            //去重
            IList<string> pyList = new List<string>();
            if (pyArray != null)
            {
                foreach (var item in pyArray)
                {
                    if (!pyList.Contains(item))
                        pyList.Add(item);
                }
                foreach (var item in pyList)
                {
                    string node = root + item;
                    //root.Child.Add(node);
                    if (nextStrChinese != "")
                        CreatePinyinList(node, nextStrChinese, format, PinyinList);
                    else
                    {
                        PinyinList.Add(node);
                    }
                }
            }
            else
            {
                if (nextStrChinese != "")
                    CreatePinyinList(root, nextStrChinese, format, PinyinList);
                else
                {
                    PinyinList.Add(root);
                }
            }

        }
        /// <summary>
        /// 递归生成拼音首字母列表
        /// </summary>
        /// <param name="root"></param>
        /// <param name="strChinese"></param>
        /// <param name="format"></param>
        /// <param name="InitialsList"></param>
        private static void CreateInitialsList(string root, string strChinese, HanyuPinyinOutputFormat format, IList<string> InitialsList)
        {
            //取第一个字符
            char c = strChinese[0];
            //取剩余字符
            string nextStrChinese = strChinese.Substring(1, strChinese.Length - 1);
            var pyArray = PinyinHelper.ToHanyuPinyinStringArray(c, format);
            //去重
            IList<string> pyList = new List<string>();
            if (pyArray != null)
            {
                foreach (var item in pyArray)
                {
                    if (!pyList.Contains(item.Substring(0, 1)))
                        pyList.Add(item.Substring(0, 1));
                }
                foreach (var item in pyList)
                {
                    string node = root + item;
                    //root.Child.Add(node);
                    if (nextStrChinese != "")
                        CreateInitialsList(node, nextStrChinese, format, InitialsList);
                    else
                    {
                        InitialsList.Add(node);
                    }
                }
            }
            else
            {
                if (nextStrChinese != "")
                    CreateInitialsList(root, nextStrChinese, format, InitialsList);
                else
                {
                    InitialsList.Add(root);
                }
            }
        }

        #endregion

        #region 流转换
        public static Stream StringToStream(string Value)
        {
            return new MemoryStream(Encoding.GetEncoding("utf-8").GetBytes(Value));
        }

        public static string StreamToString(Stream Value)
        {
            Value.Position = 0;
            using (StreamReader reader = new StreamReader(Value, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }

        }

        public static string ByteToString(byte[] Value)
        {
            return System.Text.Encoding.Default.GetString(Value);
        }

        public static byte[] StreamToByte(Stream Value)
        {
            byte[] bytes = new byte[Value.Length];
            Value.Read(bytes, 0, bytes.Length);
            Value.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
        #endregion

        #region 颜色转换
        /// <summary>
        /// [颜色：16进制转成RGB]
        /// </summary>
        /// <param name="strColor">设置16进制颜色 [返回RGB]</param>
        /// <returns></returns>
        public static System.Drawing.Color colorHx16toRGB(string strHxColor)
        {
            try
            {
                if (strHxColor.Length == 0)
                {//如果为空
                    return System.Drawing.Color.FromArgb(0, 0, 0);//设为黑色
                }
                else
                {//转换颜色
                    return System.Drawing.Color.FromArgb(System.Int32.Parse(strHxColor.Substring(1, 2), System.Globalization.NumberStyles.AllowHexSpecifier), System.Int32.Parse(strHxColor.Substring(3, 2), System.Globalization.NumberStyles.AllowHexSpecifier), System.Int32.Parse(strHxColor.Substring(5, 2), System.Globalization.NumberStyles.AllowHexSpecifier));
                }
            }
            catch
            {//设为黑色
                return System.Drawing.Color.FromArgb(0, 0, 0);
            }
        }

        /// <summary>
        /// [颜色：RGB转成16进制]
        /// </summary>
        /// <param name="R">红 int</param>
        /// <param name="G">绿 int</param>
        /// <param name="B">蓝 int</param>
        /// <returns></returns>
        public static string colorRGBtoHx16(int R, int G, int B)
        {
            return System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.FromArgb(R, G, B));
        }
        #endregion

        #region 半角全角转换
        /// <summary>
        /// 全角转半角
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToDBC(this string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }
        /// <summary>
        /// 半角转全角
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToSBC(this string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }
        #endregion

        #region 本地路径和虚拟路径转换
        /// <summary>
        /// 虚拟路径转本地路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string UrlToLocal(string url)
        {
            return System.Web.HttpContext.Current.Server.MapPath(url);
        }
        /// <summary>
        /// 本地路径转虚拟路径
        /// </summary>
        /// <param name="local"></param>
        /// <returns></returns>
        public static string LocalToUrl(string local)
        {
            string root = System.Web.HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());
            return local.Replace(root, "").Replace(@"\", @"/");
        }
        #endregion

        #region 星期中文英文转换

        public static string WeekDayEtoC(string strWeekDay)
        {
            string result = "";
            switch (strWeekDay)
            {
                case "Monday":
                    result = "周一";
                    break;
                case "Tuesday":
                    result = "周二";
                    break;
                case "Wednesday":
                    result = "周三";
                    break;
                case "Thursday":
                    result = "周四";
                    break;
                case "Friday":
                    result = "周五";
                    break;
                case "Saturday":
                    result = "周六";
                    break;
                case "Sunday":
                    result = "周日";
                    break;
            }
            return result;
        }

        #endregion

        #region 驼峰大写转换
        public static string camel2under(string c)
        {
            StringBuilder strValue = new StringBuilder();
            for (var j = 0; j < c.Length; j++)
            {
                string temp = c[j].ToString();
                if (Regex.IsMatch(temp, "[A-Z]"))
                {
                    if (strValue.Length == 0)
                    {

                    }
                    else
                    {
                        temp = "_" + temp;
                    }
                }
                strValue.Append(temp);
            }
            return strValue.ToString().ToUpper();
        }

        public static string under2camel(string s)
        {
            StringBuilder strValue = new StringBuilder();
            var list = s.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var word in list)
            {
                strValue.Append(word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower());
            }
            return strValue.ToString();
        }
        #endregion

        /// <summary>
        /// 对象克隆
        /// </summary>
        /// <typeparam name="TIn"></typeparam>
        /// <typeparam name="TOut"></typeparam>
        public static class TransExpV2<TIn, TOut>
        {
            private static readonly Func<TIn, TOut> cache = GetFunc();
            private static Func<TIn, TOut> GetFunc()
            {
                ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
                List<MemberBinding> memberBindingList = new List<MemberBinding>();

                foreach (var item in typeof(TOut).GetProperties())
                {
                    if (!item.CanWrite)
                        continue;

                    MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }

                MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
                Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });

                return lambda.Compile();
            }

            public static TOut Trans(TIn tIn)
            {
                return cache(tIn);
            }

        }
    }
}
